﻿using System.Windows;
using DSPL.Services;
using DSPL.Contracts;
using DSPL.Common;
using System.Data;
using DSPL.Services.Services;
using DSPL.Contracts.Common;
using DSPL.Contracts.ViewModel;
using DSPL.Contracts.Command;
using DSPL.Finac.Common;
using DSPL.Common.CommonControls.Controls;
using System.Windows.Media;
using System.Windows.Controls;
using System.Collections.Generic;
using System.Windows.Media.Imaging;
using System;
using System.IO;
using System.Reflection;
using System.Windows.Input;

namespace DSPL.Finac.ViewModel
{
    public class ProductMasterViewModel : BaseViewModel
    {
        private bool isItemCodeFocused;
        private bool isItemNameFocused;
        private bool isProductGroupFocused;
        private bool isProductTypeFocused;
        private bool isTaxComCodeFocused;
        private bool isProductUnitFocused;
        private bool isPriceLevelFocused;
        private bool isPurchaseAccountFocused;
        private bool isPurchaseReturnAccountFocused;
        private bool isSalesAccountFocused;
        private bool isSalesReturnAccountFocused;
        private bool isClosingStockAccountFocused;
        private bool isStockInHandAccountFocused;
        private bool isVendorCodeFocused;
        private BitmapImage _imageSourceUrl;
        private Dictionary<string, string> _bindProductGroup = new Dictionary<string, string>();
        private Dictionary<string, string> _bindProductType = new Dictionary<string, string>();
        private Dictionary<string, string> _bindPurchaseAc = new Dictionary<string, string>();
        private Dictionary<string, string> _bindPurchaseReturnAc = new Dictionary<string, string>();
        private Dictionary<string, string> _bindSalesAc = new Dictionary<string, string>();
        private Dictionary<string, string> _bindSalesReturnAc = new Dictionary<string, string>();
        private Dictionary<string, string> _bindDiscountAc = new Dictionary<string, string>();
        private Dictionary<string, string> _bindStkClosingAc = new Dictionary<string, string>();
        private Dictionary<string, string> _bindStkInHand = new Dictionary<string, string>();
        private DataTable _dtPriceLevels;
        private ICommand imageBrowseClick;
        private string _ImageSourceFile = string.Empty;
        private Image _imgAttach; 

        #region Define properties
        public bool IsItemCodeFocused
        {
            get { return isItemCodeFocused; }
            set
            {
                isItemCodeFocused = value;
                this.OnPropertyChanged("IsItemCodeFocused");
            }
        }

        public bool IsItemNameFocused
        {
            get { return isItemNameFocused; }
            set
            {
                isItemNameFocused = value;
                this.OnPropertyChanged("IsItemNameFocused");

            }
        }

        public bool IsProductGroupFocused
        {
            get { return isProductGroupFocused; }
            set
            {
                isProductGroupFocused = value;
                this.OnPropertyChanged("IsProductGroupFocused");

            }
        }

        public bool IsProductTypeFocused
        {
            get { return isProductTypeFocused; }
            set
            {
                isProductTypeFocused = value;
                this.OnPropertyChanged("IsProductTypeFocused");

            }
        }

        public bool IsTaxComCodeFocused
        {
            get { return isTaxComCodeFocused; }
            set
            {
                isTaxComCodeFocused = value;
                this.OnPropertyChanged("IsTaxComCodeFocused");

            }
        }

        public bool IsProductUnitFocused
        {
            get { return isProductUnitFocused; }
            set
            {
                isProductUnitFocused = value;
                this.OnPropertyChanged("IsProductUnitFocused");

            }
        }

        public bool IsPriceLevelFocused
        {
            get { return isPriceLevelFocused; }
            set
            {
                isPriceLevelFocused = value;
                this.OnPropertyChanged("IsPriceLevelFocused");

            }
        }

        public bool IsPurchaseAccountFocused
        {
            get { return isPurchaseAccountFocused; }
            set
            {
                isPurchaseAccountFocused = value;
                this.OnPropertyChanged("IsPurchaseAccountFocused");

            }
        }

        public bool IsPurchaseReturnAccountFocused
        {
            get { return isPurchaseReturnAccountFocused; }
            set
            {
                isPurchaseReturnAccountFocused = value;
                this.OnPropertyChanged("IsPurchaseReturnAccountFocused");

            }
        }

        public bool IsSalesAccountFocused
        {
            get { return isSalesAccountFocused; }
            set
            {
                isSalesAccountFocused = value;
                this.OnPropertyChanged("IsSalesAccountFocused");

            }
        }

        public bool IsSalesReturnAccountFocused
        {
            get { return isSalesReturnAccountFocused; }
            set
            {
                isSalesReturnAccountFocused = value;
                this.OnPropertyChanged("IsSalesReturnAccountFocused");

            }
        }

        public bool IsClosingStockAccountFocused
        {
            get { return isClosingStockAccountFocused; }
            set
            {
                isClosingStockAccountFocused = value;
                this.OnPropertyChanged("IsClosingStockAccountFocused");

            }
        }

        public bool IsStockInHandAccountFocused
        {
            get { return isStockInHandAccountFocused; }
            set
            {
                isStockInHandAccountFocused = value;
                this.OnPropertyChanged("IsStockInHandAccountFocused");

            }
        }

        public bool IsVendorCodeFocused
        {
            get { return isVendorCodeFocused; }
            set
            {
                isVendorCodeFocused = value;
                this.OnPropertyChanged("IsVendorCodeFocused");

            }
        }
        
        public Dictionary<string, string> BindProductGroup
        {
            get { return _bindProductGroup; }
            set
            {
                _bindProductGroup = value;
                this.OnPropertyChanged("BindProductGroup");

            }
        }

        public Dictionary<string, string> BindProductType
        {
            get { return _bindProductType; }
            set
            {
                _bindProductType = value;
                this.OnPropertyChanged("BindProductType");

            }
        }

        public Dictionary<string, string> BindPurchaseAc
        {
            get { return _bindPurchaseAc; }
            set
            {
                _bindPurchaseAc = value;
                this.OnPropertyChanged("BindPurchaseAc");

            }
        }


        public Dictionary<string, string> BindPurchaseReturnAc
        {
            get { return _bindPurchaseReturnAc; }
            set
            {
                _bindPurchaseReturnAc = value;
                this.OnPropertyChanged("BindPurchaseReturnAc");

            }
        }

        public Dictionary<string, string> BindSalesAc
        {
            get { return _bindSalesAc; }
            set
            {
                _bindSalesAc = value;
                this.OnPropertyChanged("BindSalesAc");

            }
        }

        public Dictionary<string, string> BindSalesReturnAc
        {
            get { return _bindSalesReturnAc; }
            set
            {
                _bindSalesReturnAc = value;
                this.OnPropertyChanged("BindSalesReturnAc");
            }
        }

        public Dictionary<string, string> BindDiscountAc
        {
            get { return _bindDiscountAc; }
            set
            {
                _bindDiscountAc = value;
                this.OnPropertyChanged("BindDiscountAc");
            }
        }

        public Dictionary<string, string> BindStkClosingAc
        {
            get { return _bindStkClosingAc; }
            set
            {
                _bindStkClosingAc = value;
                this.OnPropertyChanged("BindStkClosingAc");
            }
        }

        public Dictionary<string, string> BindStkInHand
        {
            get { return _bindStkInHand; }
            set
            {
                _bindStkInHand = value;
                this.OnPropertyChanged("BindStkInHand");
            }
        }

        public DataTable DtPriceLevels
        {
            get { return _dtPriceLevels; }
            set { _dtPriceLevels = value;
            OnPropertyChanged("DtPriceLevels");
            }
        }

        public BitmapImage ImageSourceUrl
        {
            get
            {
                return _imageSourceUrl;
            }

            set
            {
                _imageSourceUrl = value;
                OnPropertyChanged("ImageSourceUrl");
            }
        }
        #endregion

        #region Commands

        public ICommand ImageBrowseClick
        {
            get
            {
                if (this.imageBrowseClick == null)
                {
                    this.imageBrowseClick = new RelayCommand(ImageBrowseClickExecuted);
                }

                return this.imageBrowseClick;
            }
        }

        #endregion


        #region Constructor

        public ProductMasterViewModel()
            : base()
        {
            MessageTitle = "Product Master";
        }

        #endregion
        /// <summary>
        /// Validate mandatory data before save
        /// </summary>
        /// <param name="obj"></param>
        protected override void PreDataValidateExecuted(object obj)
        {
            IsItemCodeFocused = false;
            IsItemNameFocused = false;
            IsProductGroupFocused = false;
            IsProductTypeFocused = false;
            IsTaxComCodeFocused = false;
            IsProductUnitFocused = false;
            IsPriceLevelFocused = false;
            IsPurchaseAccountFocused = false;
            IsPurchaseReturnAccountFocused = false;
            IsSalesAccountFocused = false;
            IsSalesReturnAccountFocused = false;
            IsClosingStockAccountFocused = false;
            IsStockInHandAccountFocused = false;
            IsVendorCodeFocused = false;

            var messageService = new MessageService();
            if (CurrentRow["ItemCode"].ToString().Trim() == string.Empty)
            {
                messageService.ShowMessage(MessageText.ItemCodeNotEmpty, MessageTitle, MessageType.InfoOK);
                IsItemCodeFocused = true;
                this.IsValid = false;
                return;
            }

            if (CurrentRow["ItemName"].ToString().Trim() == string.Empty)
            {
                messageService.ShowMessage(MessageText.ItemNameNotEmpty, MessageTitle, MessageType.InfoOK);
                IsItemNameFocused = true;
                this.IsValid = false;
                return;
            }
            if (CurrentRow["GroupPk"] ==DBNull.Value ||  Convert.ToInt32(CurrentRow["GroupPk"]) == 0)
            {
                messageService.ShowMessage(MessageText.ProductGroupCodeNotEmpty, MessageTitle, MessageType.InfoOK);
                IsProductGroupFocused = true;
                this.IsValid = false;
                return;
            }

            if (CurrentRow["TypePk"] ==DBNull.Value || Convert.ToInt32(CurrentRow["TypePk"]) == 0)
            {
                messageService.ShowMessage(MessageText.ProductTypeCodeNotEmpty, MessageTitle, MessageType.InfoOK);
                IsProductTypeFocused = true;
                this.IsValid = false;
                return;
            }

            if (CurrentRow["TaxComPk"] == DBNull.Value || Convert.ToInt32(CurrentRow["TaxComPk"]) == 0)
            {
                messageService.ShowMessage(MessageText.TaxCombinationCodeNotEmpty, MessageTitle, MessageType.InfoOK);
                IsTaxComCodeFocused = true;
                this.IsValid = false;
                return;
            }

            if (CurrentRow["UnitPk"] == DBNull.Value || Convert.ToInt32(CurrentRow["UnitPk"]) == 0)
            {
                messageService.ShowMessage(MessageText.ProductUnitCodeNotEmpty, MessageTitle, MessageType.InfoOK);
                IsProductUnitFocused = true;
                this.IsValid = false;
                return;
            }

            string vendorCode = CurrentRow["VenPCode"].ToString().Trim();
            if (CurrentRow["VenPCode"].ToString().Trim() != string.Empty)
            {
                var masterDataRetrieve = new MasterReadService();

                if (masterDataRetrieve.IsVendorCodeExist(vendorCode, Convert.ToInt32(CurrentRow["ItemPk"])))
                {
                    messageService.ShowMessage(MessageText.VendorCodeDuplicated, MessageTitle, MessageType.InfoOK);
                    IsVendorCodeFocused = true;
                    this.IsValid = false;
                    return;
                }

            }
            else
            {
                CurrentRow["VenPCode"] = CurrentRow["ItemCode"].ToString().Trim();
            }

            if (CurrentRow["PriLvlPk"] == DBNull.Value || Convert.ToInt32(CurrentRow["PriLvlPk"]) == 0)
            {
                messageService.ShowMessage(MessageText.PriceLevelNotEmpty, MessageTitle, MessageType.InfoOK);
                IsPriceLevelFocused = true;
                this.IsValid = false;
                return;
            }

            if (DtPriceLevels.Select("PriLvlPk='" + CurrentRow["PriLvlPk"].ToString().Trim() + "' AND Price>0").Length == 0)
            {
                messageService.ShowMessage(MessageText.DefaultPriceLevelNotEmpty, MessageTitle, MessageType.InfoOK);
                IsPriceLevelFocused = true;
                this.IsValid = false;
                return;
            }
     
            this.IsValid = true;
        }

        private void DisplayDataInControls(object obj)
        {
            if (obj == null)
            {
                return;
            }
            Visual rootContainer = obj as Visual;
            if (rootContainer != null)
            {
                int ChildNumber = VisualTreeHelper.GetChildrenCount(rootContainer);

                for (int i = 0; i < ChildNumber; i++)
                {
                    Visual childVisual = (Visual)VisualTreeHelper.GetChild(rootContainer, i);

                    if ((childVisual.GetType() == typeof(TabControl) || (childVisual.GetType() == typeof(Grid)) || (childVisual.GetType() == typeof(Border))) && (VisualTreeHelper.GetChildrenCount(childVisual) > 0))
                    {
                        if (childVisual.GetType() == typeof(TabControl))
                        {
                            foreach (TabItem tb in ((TabControl)childVisual).Items)
                            {
                                DisplayDataInControls(((System.Windows.Controls.Grid)tb.Content));
                            }
                        }
                        else
                        {
                            DisplayDataInControls(childVisual);
                        }
                    }
                    else
                    {
                        if (childVisual.GetType() == typeof(TxtMasterData))
                        {
                            ((TxtMasterData)childVisual).LinkObjectRefresh();
                        }
                    }
                }
            }
        }

        protected override void RefreshExternalDataObjectsExecueted(object obj)
        {
            base.RefreshExternalDataObjectsExecueted(obj);
            DisplayDataInControls(obj);
            SetPriceLevelData();
            string fileName= GetImage(CurrentRow["ItemCode"].ToString().Trim());
            if (fileName != string.Empty)
            {
              //  ImageSourceUrl = BitmapFromUri(new Uri(fileName));
            }
            else
            {
                ImageSourceUrl = null;
            }

        }

        public ImageSource BitmapFromUri(Uri source)
        {
            var bitmap = new BitmapImage();
            bitmap.BeginInit();
            bitmap.UriSource = source;
            bitmap.CacheOption = BitmapCacheOption.OnLoad;
            bitmap.CreateOptions = BitmapCreateOptions.IgnoreImageCache;
            bitmap.EndInit();

            return bitmap;
        }

        protected override void SetDataSourcesAndProperties()
        {
            BindProductGroup.Add("GroupName", "txtProductGroupTitle");
            BindProductType.Add("TypeName", "txtProductTypeTitle");
            BindPurchaseAc.Add("AccDesc","txtPurchaseAcTitle");
            BindPurchaseReturnAc.Add("AccDesc","txtPurchaseReturnAcTitle");
            BindSalesAc.Add("AccDesc","txtSalesAcTitle");
            BindSalesReturnAc.Add("AccDesc","txtSalesReturnAcTitle");
            BindDiscountAc.Add("AccDesc", "txtDiscountAcTitle");
            BindStkClosingAc.Add("AccDesc","txtClosingStockAcTitle");
            BindStkInHand.Add("AccDesc", "txtStockInHandAcTitle");            

        }

        private void SetPriceLevelData()
        {
            var masterDataRetrive = new MasterReadService();
            if (CurrentRow["ItemPk"] == DBNull.Value)
            {
                CurrentRow["ItemPk"] = 0;
            }
            DtPriceLevels = masterDataRetrive.GetItemPriceLevels(Convert.ToInt32((CurrentRow["ItemPk"])));

        }

        private string GetImage(string itemCode)
        {
            string fileName = string.Empty;
                        
            string path =(@GlobalVariables.AttachmentFolderPath);

            if (Directory.Exists(path))
            {
                string[] attachmentFiles = Directory.GetFiles(@path);

                string fileNameWithOutExt = string.Empty;
                fileName = string.Empty;
                foreach (var selectedFile in attachmentFiles)
                {
                    fileNameWithOutExt = Path.GetFileNameWithoutExtension(selectedFile);
                    if (fileNameWithOutExt.Equals(itemCode))
                    {
                        fileName = Path.GetFullPath(selectedFile);                        
                        break;
                    }
                }
            }
            else
            {
                var messageService = new MessageService();
                messageService.ShowMessage(MessageText.AttachFolderNotEixst,MessageTitle,MessageType.InfoOK);
            }
            return fileName;
            
        }

        protected override void PreDataDeleteExecuted(object obj)
        {
            var commonService = new MasterWriteService();
            var sqlTran = this.SqlTran;
            if (!commonService.DeleteProductSpecificData(Convert.ToInt32(CurrentRow["ItemPk"]), ref sqlTran))
            {
                this.IsValid = false;
            }
            else
            {
                this.IsValid = true;
                this.SqlTran = sqlTran;
            }

        }

        protected override void PostDataUpdateExecuted(object obj)
        {
            var commonService = new MasterWriteService();
            var sqlTran = this.SqlTran;
            if (!commonService.UpdateProductPriceData(CurrentRow, DtPriceLevels, ref sqlTran))
            {
                this.IsValid = false;
            }
            else
            {
                this.IsValid = true;
                this.SqlTran = sqlTran;
            }
        }

              

        protected override void PostDataInsertExecuted(object obj)
        {
            var commonService = new MasterWriteService();
            var sqlTran = this.SqlTran;
            if (!commonService.UpdateProductPriceData(CurrentRow, DtPriceLevels, ref sqlTran))
            {
                this.IsValid = false;
            }
            else
            {
                this.IsValid = true;
                this.SqlTran = sqlTran;
            }
        }
        

        public void ImageBrowseClickExecuted(object obj)
        {
            Microsoft.Win32.OpenFileDialog dlgProductImage = new Microsoft.Win32.OpenFileDialog();
            dlgProductImage.Filter = "BMP|*.bmp|GIF|*.gif|JPG|*.jpg;*.jpeg|PNG|*.png|TIFF|*.tif;*.tiff|ICO|*.ico";
            
            Nullable<bool> isSelectedFile = dlgProductImage.ShowDialog();
            _imgAttach = (Image)obj;
            if (isSelectedFile == true)
            {
                string imageFile = dlgProductImage.FileName;
             //   _imgAttach.Source = );
                _ImageSourceFile = imageFile;
               // ImageSourceUrl = imageFile;
                ImageSourceUrl = new BitmapImage(new Uri(imageFile));
            }
        }

        protected override void PostDataSaveProcessExecuted(object obj)
        {
            string fileName;
            string itemCode = CurrentRow["ItemCode"].ToString().Trim();
            fileName = GetImage(CurrentRow["ItemCode"].ToString().Trim());
            try
            {
                string fileExtension = Path.GetExtension(_ImageSourceFile);
                string targetPath = @GlobalVariables.AttachmentFolderPath + "\\" + itemCode + fileExtension;

                ImageSourceUrl = null;
                if ((fileName != string.Empty) && (_ImageSourceFile != string.Empty))
                {
                    if (File.Exists(fileName))
                    {

                        File.Delete(fileName);
                    }                 
               
                }
                
                if (_ImageSourceFile != string.Empty)
                {                  

                    File.Copy(_ImageSourceFile, targetPath);
                                      
                }
            }

            catch (Exception ex)
            {
                var messageService = new MessageService();
                messageService.ShowMessage(MessageText.ErrorCopyingAttachment, MessageTitle, MessageType.InfoOK);

            }
        }
    }
}